Popular Searches
Popular Course Categories
Popular Courses

Working with Variables and Naming Conventions

Working with Variables and Naming Conventions

Java Syntax, Variables, and Data Types

Working with Variables and Naming Conventions

Course: Core Java Training

Topic: Working with Variables and Naming Conventions

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Variables in Java

Variables are fundamental building blocks of Java programming. A variable is a named storage location used to represent data that a program needs to access or manipulate. Variables allow developers to store numbers, text, logical values, object references, and other information while a program executes.

For example, a student management application may use variables to store a student's name, age, roll number, marks, and examination result. A banking application may use variables to represent an account number, transaction amount, and account status.

In Java, every variable has a name and a type. The type determines which values can be stored and which operations are permitted. Depending on where a variable is declared, it may have a particular scope, lifetime, and initialization requirement.

Learning Objectives

  • Understand what variables are and why they are used.
  • Learn how to declare, initialize, and update variables.
  • Understand primitive and reference-type variables.
  • Explore local variables, instance variables, and static variables.
  • Learn Java identifier rules and naming conventions.
  • Understand constants and the use of final.
  • Learn variable scope, lifetime, and initialization rules.
  • Identify common variable-related errors.
  • Practice writing readable Java programs using meaningful names.

2. What Is a Variable?

A variable is a named entity declared with a type. It allows a program to refer to a value or, for reference types, to an object reference.

Basic Example

public class VariableExample {
    public static void main(String[] args) {
        int age = 22;
        String name = "Aarav";
        double percentage = 87.5;

        System.out.println(name);
        System.out.println(age);
        System.out.println(percentage);
    }
}

Output:

Aarav
22
87.5

Explanation

  • int age = 22; declares an integer variable named age and initializes it with the value 22.
  • String name = "Aarav"; declares a reference variable named name and initializes it with a reference to a string.
  • double percentage = 87.5; declares a variable that can represent a double-precision floating-point value.
  • System.out.println() displays the values on the console.

3. Variable Declaration, Initialization, and Assignment

Working with variables involves three important operations: declaration, initialization, and assignment.

3.1 Variable Declaration

Declaration introduces a variable by specifying its type and name.

int age;
String studentName;
double salary;

These declarations specify the types and names of the variables. Local variables declared this way cannot be read until they have been definitely assigned a value.

3.2 Variable Initialization

Initialization provides a variable with its initial value.

int age = 21;
String studentName = "Priya";
double salary = 45000.75;

3.3 Assignment

Assignment gives a variable a value after its declaration or replaces its existing value.

int score = 60;
score = 75;
score = 90;

System.out.println(score);

Output:

90

The variable score is updated twice. Its final value is 90.

3.4 Declaration and Initialization Together

int quantity = 10;
double price = 199.99;
boolean isAvailable = true;

Declaring and initializing a variable in one statement is common practice because it makes the initial value clear.

4. Java Data Types and Variables

Java provides primitive data types for basic values and reference types for objects and arrays. Choosing the appropriate type improves clarity and helps prevent invalid operations.

4.1 Primitive Data Types

Data Type Typical Size Example Purpose
byte 8 bits byte level = 5; Small signed integer values
short 16 bits short year = 2026; Signed integer values within a smaller range than int
int 32 bits int count = 100; General-purpose integer values
long 64 bits long population = 8000000L; Large integer values
float 32 bits float rate = 2.5f; Single-precision floating-point values
double 64 bits double price = 99.99; Double-precision floating-point values
char 16 bits char grade = 'A'; A single UTF-16 code unit
boolean Size is JVM-dependent in storage boolean passed = true; Logical values: true or false

Java primitive types have defined value ranges and behavior. The actual memory used to represent a local variable or field may depend on the JVM implementation and context.

4.2 Reference Types

Reference types include classes, interfaces, arrays, and other object-related types. A reference variable holds a reference to an object or may hold null.

String city = "Mumbai";
int[] marks = {85, 90, 78};
Student student = new Student();

In this example, city, marks, and student are reference variables. The referenced objects or arrays hold their own data.

4.3 Primitive and Reference Variables Compared

Feature Primitive Variable Reference Variable
Examples int, double, boolean String, arrays, custom classes
What it holds A value of its primitive type A reference to an object or null
Can be null? No Yes, if the type permits a null reference
Example int age = 20; String name = "Aarav";

5. Types of Variables in Java

Java variables can be classified according to where they are declared. The three common categories are local variables, instance variables, and class variables.

5.1 Local Variables

A local variable is declared inside a method, constructor, or block. Its scope is limited to the relevant method or block.

public class LocalVariableExample {
    public static void main(String[] args) {
        int number = 10;

        if (number > 5) {
            String message = "Number is greater than five";
            System.out.println(message);
        }

        System.out.println(number);
    }
}

The variable number is available throughout the body of main() after its declaration. The variable message is only available inside the if block.

Important: Local variables do not receive automatic default values. They must be definitely assigned before they are read.

5.2 Instance Variables

An instance variable is a non-static field declared in a class. Each object has its own instance of that field.

public class Employee {
    String employeeName;
    double salary;

    public void displayDetails() {
        System.out.println(employeeName);
        System.out.println(salary);
    }

    public static void main(String[] args) {
        Employee employee1 = new Employee();
        employee1.employeeName = "Aarav";
        employee1.salary = 35000;

        Employee employee2 = new Employee();
        employee2.employeeName = "Priya";
        employee2.salary = 42000;

        employee1.displayDetails();
        employee2.displayDetails();
    }
}

Each Employee object has its own employeeName and salary values. Updating one object's fields does not automatically change the corresponding fields of another object.

5.3 Static or Class Variables

A static variable is declared with the static keyword. It belongs to the class rather than to each individual object. A static field normally has one shared value for that class at a given time.

public class Employee {
    String employeeName;
    static String companyName = "ABC Technologies";

    public Employee(String name) {
        employeeName = name;
    }

    public void displayDetails() {
        System.out.println(employeeName + " works at " + companyName);
    }

    public static void main(String[] args) {
        Employee employee1 = new Employee("Aarav");
        Employee employee2 = new Employee("Priya");

        employee1.displayDetails();
        employee2.displayDetails();
    }
}

Both objects use the shared companyName field. Static fields are commonly used for class-wide state and constants, but shared mutable state should be designed carefully.

5.4 Method Parameters

Parameters are variables declared in a method or constructor signature. They receive argument values when the method or constructor is invoked.

public class Calculator {
    public int add(int firstNumber, int secondNumber) {
        return firstNumber + secondNumber;
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.add(10, 20));
    }
}

Here, firstNumber and secondNumber are parameters. The values 10 and 20 are the arguments passed to the method.

6. Variable Scope and Lifetime

Scope determines where a variable can be accessed in source code. Lifetime refers to how long the variable or its associated storage exists during program execution.

Variable Type Scope General Lifetime Default Initialization
Local variable Within its declaring block or method During execution of the relevant block or method, subject to language and runtime rules No automatic default value for reading purposes
Instance field According to class and access rules, through an object While the object remains reachable and is not reclaimed Receives a default value before explicit initialization
Static field According to class and access rules Associated with the class while it remains loaded, subject to class unloading Receives a default value before explicit initialization
Parameter Within its method, constructor, or applicable declaration context During execution of the relevant invocation Receives the argument value when the method or constructor is invoked

Example of Scope

public class ScopeExample {
    public static void main(String[] args) {
        int outerNumber = 10;

        if (outerNumber > 0) {
            int innerNumber = 20;
            System.out.println(innerNumber);
        }

        System.out.println(outerNumber);
        // System.out.println(innerNumber); // Compilation error
    }
}

The variable innerNumber cannot be accessed outside the block in which it was declared.

7. Understanding Variable Initialization and Default Values

Java treats local variables differently from fields. Instance and static fields receive default values before their explicit initialization. Local variables must be assigned before use.

Field Type Default Value
byte, short, int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Reference types null

Example

public class DefaultValueExample {
    int number;
    boolean active;
    String name;

    public void display() {
        System.out.println(number);
        System.out.println(active);
        System.out.println(name);
    }

    public static void main(String[] args) {
        DefaultValueExample example = new DefaultValueExample();
        example.display();
    }
}

Output:

0
false
null

The values shown are defaults for instance fields. If you declare a local variable without initializing it and then try to read it, the compiler reports that the variable might not have been initialized.

8. Rules for Naming Variables in Java

A variable name is an identifier that allows a program to refer to a variable. Java defines rules for valid identifiers, while naming conventions provide recommendations that make source code easier to read.

8.1 Identifier Rules

  • An identifier must begin with a valid Java identifier-start character, such as a letter, underscore, or dollar sign.
  • Digits may appear after the first character but cannot be the first character.
  • Java identifiers are case-sensitive.
  • Whitespace is not permitted inside an identifier.
  • Reserved keywords cannot be used as ordinary identifiers.
  • Identifiers may contain valid Unicode characters, not just English letters.
  • A single underscore cannot be used as an ordinary identifier in modern Java.

8.2 Valid and Invalid Names

Variable Name Valid? Explanation
studentName Yes Descriptive name following common conventions.
age Yes Starts with a letter.
marks2 Yes A digit appears after the first character.
_count Yes Valid under modern Java identifier rules, though the initial underscore is discouraged by convention.
$price Yes Valid, but dollar signs are generally avoided in developer-defined variable names.
2marks No An identifier cannot start with a digit.
student name No Contains whitespace.
class No It is a reserved keyword.
total-amount No The hyphen is not permitted in an identifier.
first.name No, as one identifier The dot is not permitted inside a single identifier.
_ No, as an ordinary identifier A single underscore is reserved in modern Java.

9. What Are Naming Conventions?

Naming conventions are widely accepted practices for choosing names for variables, fields, methods, classes, packages, and constants. They are not all compiler-enforced rules. Instead, they improve consistency and make code easier for other developers to understand.

For Java variables, the most common convention is camelCase: start with a lowercase letter and capitalize the first letter of each subsequent word.

Examples

String firstName = "Aarav";
int studentAge = 21;
double monthlySalary = 50000.00;
boolean isAccountActive = true;

These names communicate what each variable represents without requiring the reader to inspect every line of code.

10. CamelCase Naming Convention

CamelCase is a naming style in which multiple words are joined together without spaces, with internal words beginning with uppercase letters.

10.1 Lower CamelCase

Lower camelCase begins with a lowercase letter. It is commonly used for variables, fields, parameters, and method names.

String customerName;
int totalMarks;
double accountBalance;
boolean isEligible;
int calculateTotal() {
    return 100;
}

10.2 Upper CamelCase or PascalCase

PascalCase begins with an uppercase letter. It is commonly used for class, interface, enum, and record names.

class StudentDetails {
}

class BankAccount {
}

10.3 When to Use Each Style

Element Recommended Style Example
Variable lower camelCase studentName
Instance field lower camelCase accountBalance
Static field lower camelCase, unless it is a constant employeeCount
Method lower camelCase calculateSalary()
Class PascalCase EmployeeDetails
Interface PascalCase PaymentService
Package Lowercase com.example.student
Constant Uppercase with underscores MAX_LOGIN_ATTEMPTS

11. Choosing Meaningful Variable Names

A good variable name describes the purpose of the data. Meaningful names reduce confusion, improve readability, and make debugging easier.

Weak Names and Better Alternatives

Weak Name Better Name Reason
x studentAge Clearly identifies the data.
amt paymentAmount Uses a more descriptive name.
n numberOfStudents Explains what the number represents.
data customerRecords Provides more context.
flag isPaymentComplete Makes the Boolean meaning clearer.
temp calculatedTotal Describes the variable's role.

Short variable names can be appropriate in small scopes, especially for loop counters such as i and j. For variables used throughout a method or class, prefer names that communicate their purpose.

12. Naming Boolean Variables

Boolean variables represent logical states, such as whether a user is active, a payment is complete, or an order has been shipped. Names that read like questions or conditions make Boolean expressions easier to understand.

Examples

boolean isLoggedIn = true;
boolean hasPermission = false;
boolean isPaymentComplete = true;
boolean canSubmitForm = false;

These names make conditions easy to read:

if (isLoggedIn) {
    System.out.println("Welcome back");
}

if (hasPermission) {
    System.out.println("Access granted");
}

Prefixes such as is, has, and can are common conventions, not strict language rules.

13. Naming Numeric and Monetary Variables

Numeric variables should indicate the quantity or measurement they represent. For financial calculations, use a type appropriate to the required precision. In many business applications, BigDecimal is preferred for decimal monetary arithmetic because binary floating-point types such as double cannot represent every decimal fraction exactly.

Examples

int numberOfEmployees = 150;
double averageTemperature = 28.5;
long populationCount = 12000000L;

Example for Monetary Values

import java.math.BigDecimal;

public class PaymentExample {
    public static void main(String[] args) {
        BigDecimal productPrice = new BigDecimal("199.99");
        BigDecimal deliveryCharge = new BigDecimal("40.00");
        BigDecimal totalAmount = productPrice.add(deliveryCharge);

        System.out.println("Total: " + totalAmount);
    }
}

Output:

Total: 239.99

Using string-based decimal construction avoids first converting an inexact binary floating-point value into a BigDecimal.

14. Constants and the final Keyword

A constant is a value intended not to be reassigned after initialization. In Java, the final keyword prevents a variable from being assigned again after it has been initialized, subject to Java's definite-assignment rules.

Example

public class ConstantExample {
    static final double PI = 3.141592653589793;
    static final int MAX_LOGIN_ATTEMPTS = 5;

    public static void main(String[] args) {
        System.out.println(PI);
        System.out.println(MAX_LOGIN_ATTEMPTS);
    }
}

Constant Naming Convention

Constants that are declared using static final and represent shared constant values are conventionally named using uppercase letters with underscores between words.

static final int MAX_USERS = 100;
static final double TAX_RATE = 0.18;
static final String DEFAULT_LANGUAGE = "English";

Note that final prevents reassignment of a reference variable, but it does not automatically make the referenced object immutable. For example, a final reference to a mutable list can still refer to a list whose contents change.

15. Naming Conventions for Different Java Elements

Java Element Recommended Convention Example
Local variable Lower camelCase totalMarks
Instance field Lower camelCase employeeName
Static field Lower camelCase for ordinary mutable state activeEmployeeCount
Constant Uppercase with underscores DEFAULT_TIMEOUT
Method Lower camelCase, usually a verb or verb phrase calculateInterest()
Class PascalCase, usually a noun BankAccount
Interface PascalCase RunnableTask
Package Lowercase com.justacademy.training
Enum type PascalCase OrderStatus
Enum constant Uppercase with underscores ORDER_PENDING

16. Variable Shadowing

Variable shadowing occurs when a variable declared in an inner scope or a field is obscured by another variable with the same name in a nested context. It can make code confusing if not handled carefully.

Example

public class ShadowingExample {
    private int score = 50;

    public void displayScore() {
        int score = 90;
        System.out.println(score);
        System.out.println(this.score);
    }

    public static void main(String[] args) {
        ShadowingExample example = new ShadowingExample();
        example.displayScore();
    }
}

Output:

90
50

The local variable score takes precedence when the simple name is used inside the method. The expression this.score explicitly refers to the instance field.

To avoid unnecessary confusion, choose distinct names when local variables and fields represent different concepts. Using the same parameter and field name in constructors is common, but it should be handled clearly with this.

17. Variable Naming in Constructors and Methods

Parameters should describe the information supplied to a method or constructor. When a constructor parameter has the same name as an instance field, the this keyword can distinguish the field from the parameter.

Example

public class Product {
    private String productName;
    private double productPrice;

    public Product(String productName, double productPrice) {
        this.productName = productName;
        this.productPrice = productPrice;
    }

    public void displayProduct() {
        System.out.println(productName);
        System.out.println(productPrice);
    }

    public static void main(String[] args) {
        Product product = new Product("Keyboard", 799.00);
        product.displayProduct();
    }
}

In this example:

  • productName and productPrice declared at class level are instance fields.
  • The names in the constructor's parameter list refer to the parameters.
  • this.productName and this.productPrice refer to the current object's fields.

18. Common Variable Errors and How to Fix Them

Error Incorrect Example Correction
Using a local variable before initialization int total; System.out.println(total); Assign a value before reading it.
Using an invalid identifier int 2count = 5; Use a valid name such as count2.
Using a keyword as a name int class = 10; Use a name such as classCount.
Assigning an incompatible type int age = "twenty"; Use a compatible value, such as int age = 20;.
Incorrect capitalization studentage when the variable is declared as studentAge Use the exact same capitalization.
Reassigning a final variable final int LIMIT = 10; LIMIT = 20; Do not reassign a final variable.
Using an out-of-scope variable Reading a block-local variable outside its block Declare the variable in a suitable enclosing scope if appropriate.
Unclear variable name double a = 1500; Prefer a meaningful name such as monthlyRent.

19. Best Practices for Working With Variables

  • Choose the data type that best represents the intended value.
  • Use descriptive names that communicate a variable's purpose.
  • Follow lower camelCase for variables and fields.
  • Use uppercase with underscores for shared constants declared using static final.
  • Initialize local variables before reading them.
  • Keep variables within the smallest scope that reasonably supports their use.
  • Avoid reusing a variable for unrelated purposes.
  • Use Boolean names that make conditions easy to understand.
  • Avoid unnecessary abbreviations and ambiguous names.
  • Use final when reassignment is not intended.
  • Keep mutable shared static state to a minimum.
  • Use appropriate types for financial calculations and other precision-sensitive work.
  • Follow the established naming style of the project.
  • Compile and test programs frequently to detect mistakes early.

20. Practical Example: Student Information System

The following program demonstrates local variables, instance fields, a constant, meaningful names, and a method.

public class Student {
    private String studentName;
    private int studentAge;
    private double marks;

    private static final double PASS_MARKS = 40.0;

    public Student(String studentName, int studentAge, double marks) {
        this.studentName = studentName;
        this.studentAge = studentAge;
        this.marks = marks;
    }

    public void displayDetails() {
        boolean hasPassed = marks >= PASS_MARKS;

        System.out.println("Student Name: " + studentName);
        System.out.println("Student Age: " + studentAge);
        System.out.println("Marks: " + marks);
        System.out.println("Passed: " + hasPassed);
    }

    public static void main(String[] args) {
        Student student = new Student("Aarav", 21, 85.5);
        student.displayDetails();
    }
}

Expected Output

Student Name: Aarav
Student Age: 21
Marks: 85.5
Passed: true

Concepts Demonstrated

  • studentName, studentAge, and marks are instance fields.
  • PASS_MARKS is a shared constant.
  • The constructor parameters receive values when an object is created.
  • hasPassed is a local variable.
  • The method displayDetails() prints the student's information.
  • The names communicate the purpose of each variable.

21. Practical Exercise: Employee Salary Calculator

Create a Java program that stores employee information, calculates a bonus, and displays the final salary. Use meaningful names and appropriate data types.

Starter Code

public class EmployeeSalary {
    public static void main(String[] args) {
        String employeeName = "Priya";
        double basicSalary = 40000.00;
        double bonusRate = 0.10;

        double bonusAmount = basicSalary * bonusRate;
        double finalSalary = basicSalary + bonusAmount;

        System.out.println("Employee: " + employeeName);
        System.out.println("Basic Salary: " + basicSalary);
        System.out.println("Bonus Amount: " + bonusAmount);
        System.out.println("Final Salary: " + finalSalary);
    }
}

Expected Output

Employee: Priya
Basic Salary: 40000.0
Bonus Amount: 4000.0
Final Salary: 44000.0

Practice Tasks

  1. Change the employee name and basic salary.
  2. Calculate the bonus using a different bonus rate.
  3. Rename variables using lower camelCase if necessary.
  4. Create a constant named DEFAULT_BONUS_RATE.
  5. Try using an invalid identifier and observe the compiler error.
  6. Modify the program to calculate the salary of two employees.

22. Interview Questions and Answers

Q1. What is a variable in Java?

A variable is a named entity declared with a type that allows a program to store or refer to data.

Q2. What is the difference between declaration and initialization?

Declaration introduces a variable and specifies its type and name. Initialization provides its initial value.

Q3. What are the main types of variables in Java?

The common categories are local variables, instance variables, and static or class variables. Method and constructor parameters are also variables.

Q4. What is a local variable?

A local variable is declared within a method, constructor, or block and is accessible only within its applicable scope.

Q5. What is an instance variable?

An instance variable is a non-static field declared in a class. Each object has its own instance of the field.

Q6. What is a static variable?

A static variable is a class-level field declared with the static keyword. It is shared by instances of that class, subject to the class's lifecycle.

Q7. What are naming conventions?

Naming conventions are recommended practices for naming variables and other program elements. They improve readability and consistency but are not all enforced by the compiler.

Q8. What is camelCase?

CamelCase joins words without spaces and capitalizes internal words. Variable names generally use lower camelCase, such as studentName.

Q9. Can a Java variable name begin with a number?

No. A Java identifier cannot begin with a digit, although digits may appear after the first character.

Q10. Are Java variable names case-sensitive?

Yes. For example, totalMarks and TotalMarks are different identifiers.

Q11. What is a constant in Java?

A constant is a value intended not to be reassigned. The final keyword prevents reassignment after initialization, and shared constants are commonly declared static final.

Q12. Do local variables receive default values?

No. A local variable must be definitely assigned before it is read. Instance and static fields receive default values.

Q13. What is variable shadowing?

Variable shadowing occurs when a variable declared in a nested context has the same name as another variable, making the outer variable less directly accessible by its simple name.

Q14. Why should meaningful variable names be used?

Meaningful names make the code easier to understand, maintain, debug, and review.

Q15. What is the difference between a primitive variable and a reference variable?

A primitive variable stores a value of a primitive type. A reference variable holds a reference to an object or may contain null.

23. Quick Revision Checklist

  • A variable is declared using a type and a name.
  • Initialization assigns an initial value to a variable.
  • Assignment can update a variable's value when reassignment is permitted.
  • Java supports eight primitive data types.
  • Reference variables can refer to objects or contain null.
  • Local variables must be definitely assigned before use.
  • Instance fields belong to individual objects.
  • Static fields belong to the class rather than to each object separately.
  • Variable names are case-sensitive.
  • Identifiers cannot begin with a digit or contain whitespace.
  • Variables generally follow lower camelCase naming conventions.
  • Classes generally follow PascalCase naming conventions.
  • Shared constants commonly use uppercase letters and underscores.
  • The final keyword prevents reassignment after initialization.
  • Good variable names improve readability and maintainability.

24. Conclusion

Working with variables and naming conventions is an essential part of learning Core Java. Variables allow programs to store and manipulate information, while appropriate data types help ensure that values are used correctly. Understanding local, instance, and static variables also helps developers manage scope and shared state effectively.

Following Java naming conventions makes source code easier to read, debug, test, and maintain. Use meaningful lower camelCase names for variables, descriptive names for fields and parameters, and uppercase underscore-separated names for shared constants. Combine these practices with appropriate initialization, limited scope, and regular testing to develop clean and reliable Java programs.

Continue learning with the Core Java Training course at JustAcademy. You can register for a course demo or visit the JustAcademy homepage to explore more learning resources.

whatsapp